package com.shyroke.daydayzhuanweb.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuanapi.dto.*;
import com.shyroke.daydayzhuanapi.entity.*;
import com.shyroke.daydayzhuanapi.mapper.AppMapper;
import com.shyroke.daydayzhuanapi.mapper.LabelMapper;
import com.shyroke.daydayzhuanapi.mapper.ProjectMapper;
import com.shyroke.daydayzhuanapi.mapper.UserMapper;
import com.shyroke.daydayzhuandao.respository.*;
import com.shyroke.daydayzhuansvc.service.IOSSService;
import com.shyroke.daydayzhuansvc.service.IProjectService;
import com.shyroke.daydayzhuansvc.service.ISysDownService;
import com.shyroke.daydayzhuansvc.service.impl.*;
import com.shyroke.daydayzhuansvc.util.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/11/16 11:32
 */
@Controller
public class HomeController {

    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private TypeRepository typeRepository;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IOSSService ossServicec;
    @Autowired
    private TypeService typeService;
    @Autowired
    private LabelRepository labelRepository;
    @Autowired
    private ISysDownService sysDownService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private AppService appService;

    @Value("${sitemap.path}")
    private String siteMapPath;

    @Value("${sitemap.name}")
    private String siteMapName;
    @Autowired
    private OSSService ossService;
    @Autowired
    private AppLabelRepository appLabelRepository;
    @Autowired
    private AppRepository appRepository;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AppMapper appMapper;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private AdvertService advertService;
    @Autowired
    private SearchLogRepository searchLogRepository;
    @Autowired
    private LabelMapper labelMapper;

    private static final String apkName = "天天线报.apk";


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 首页
     * @param model
     * @return
     */
    @GetMapping(value = "/")
    public ModelAndView index4(ModelAndView model,HttpServletRequest request,Page page,HttpServletResponse response){
        Gson gson = new Gson();
        long start3 = System.currentTimeMillis();
        model = UserUtils.getMenuList(model,null);

        /**
         * 获取轮播图的广告项目
         */
        List<ProjectCommentDto> commentProjectList = projectService.getCommentProjectList();

        for(ProjectCommentDto project:commentProjectList){
            if(!StringUtils.isEmpty(project.getCover())){
                project.setCover(ossServicec.getImgUrl(project.getCover()));
            }
        }

        Map<TypeDto,List<ProjectDto>> projectTypeMap1 =  new HashMap<>();
        Map<TypeDto,List<ProjectDto>> projectTypeMap =  new HashMap<>();

        List<TypeDto> typeList = typeService.getTypeList();
        List<Integer> typeIdList = new ArrayList<>();
        Map<Integer,TypeDto> typeMap = new HashMap<>();
        for(TypeDto type:typeList){
            typeIdList.add(type.getId());
            typeMap.put(type.getId(),type);
        }

        List<ProjectDto> typeProjectList = projectService.getProjectListByTypeId(typeIdList,typeMap);
        for(ProjectDto project:typeProjectList){
            boolean showFlag = CommonUtil.in24Hour(new Date(),project.getCreateTime());
            project.setIsToday(showFlag == true ? "1":"0");
            project.setShowCreateTime(CommonUtil.getDateByFormat(project.getCreateTime(),"MM-dd"));

            TypeDto projectType = typeMap.get(project.getTypeObj().getId());
            List<ProjectDto> list = projectTypeMap1.get(projectType);
            if(list == null){
                list = new ArrayList<>();
                list.add(project);
                projectTypeMap1.put(projectType,list);
            }else{
                list.add(project);
            }
        }

        projectTypeMap = sortMapByKey(projectTypeMap1);

        List<ProjectDto> newProject = projectService.getNewProjectList(20);
        for(ProjectDto project:newProject){
            TypeDto typeDto = typeMap.get(project.getTypeId());
            project.setTypeObj(typeDto);
            boolean showFlag = CommonUtil.in24Hour(new Date(),project.getCreateTime());
            project.setIsToday(showFlag == true ? "1":"0");
            if(project.getCreateTime() != null){
                project.setShowCreateTime(CommonUtil.getDateByFormat(project.getCreateTime(),"MM-dd"));
            }
        }

        if(!CollectionUtils.isEmpty(newProject)){
            model.addObject("upDate",DateUtils.format(newProject.get(0).getCreateTime(),"yyyy-MM-dd'T'HH:mm:ss"));
        }
        model.addObject("typeId",0);
        List<List<ProjectCommentDto>> commentProjectListList = HomeController.averageAssign(commentProjectList, 2);
        model.addObject("commentProjectList1",commentProjectListList.get(0));
        model.addObject("commentProjectList2",commentProjectListList.get(1));
        model.addObject("projectListMap", projectTypeMap);
        model.addObject("newProject", newProject.subList(0,10));
        model.addObject("newProject2", newProject.subList(10,20));
        page.setCount(projectTypeMap1.size());
        model.addObject("page", gson.toJson(page));
        boolean mobile = BrowserUtils.isMobile(request.getHeader("user-agent"));
        model.addObject("mobile", mobile);
        model.addObject("isSpider", CommonUtil.isSpider(request));

        //最新反馈6条
        List<ProcessProjectDto> withDrawList = projectService.getWithDrawListHome(null);

        //获取今日免费赚
        BigDecimal profitToday = projectService.getProfitToday();

        //获取薅羊毛文章数
        Integer articleCount = projectService.getYangmaoArticleCount();
        model.addObject("articleCount", articleCount);
        //获取累积可赚金额
        BigDecimal allProfit = projectService.getAllProfit();
        model.addObject("allProfit", allProfit.intValue());

        //app排行
        List<AppDto> appList = appService.findByTop(10,false);
        model.addObject("appList", appList);
        model.addObject("profitToday", profitToday);
        model.addObject("withDrawList", withDrawList);
        System.out.println("总耗时:"+(System.currentTimeMillis() - start3));
        model.setViewName("index");
        return model;
    }

    /**
     * 首页
     * @param model
     * @return
     */
    @GetMapping(value = "/index/{id}")
    public ModelAndView index3(ModelAndView model,HttpServletRequest request,Page page,@PathVariable("id")Integer menuId,HttpServletResponse response){
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com");
        return null;
    }


    /**
     *
     * @param model
     * @return
     */
    @GetMapping(value = "/type/{id}")
    public String typeId(ModelAndView model,HttpServletRequest request,HttpServletResponse response,@PathVariable("id")Integer typeId){
        TypeEntity type = typeRepository.findById(typeId).get();
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com"+type.getHref());
        return null;
    }

    /**
     * 首页
     * @param model
     * @return
     */
    @GetMapping(value = "/index")
    public ModelAndView index2(ModelAndView model,HttpServletRequest request,Page page,HttpServletResponse response){
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com");
        return null;
    }

    /**
     * 作者详情页
     * @param model
     * @return
     */
    @GetMapping(value = "/author/{id}")
    public ModelAndView author(ModelAndView model, @PathVariable("id")Integer uid, Page page, HttpServletResponse response){

        Gson gson = new Gson();
        model = UserUtils.getMenuList(model,null);

        Optional<UserEntity> optionalUser = userRepository.findById(uid);
        if(!optionalUser.isPresent()){
            model.setViewName("error/404");
            response.setStatus(HttpStatus.SC_NOT_FOUND);
            return model;
        }
        UserEntity user = optionalUser.get();
        if(!StringUtils.isEmpty(user.getTouxiang())){
            user.setTouxiang(ossServicec.getImgUrl(user.getTouxiang()));
        }

//        //前10条
        List<ProjectEntity> projectList = projectRepository.getNewProjectListFiveByUserId(user.getId(),10);
        if(!CollectionUtils.isEmpty(projectList)){
            for (ProjectEntity project : projectList) {
                project.setShowCreateTime(CommonUtil.getDateByFormat(project.getCreateTime(),"yyyy-MM-dd"));
            }
        }

        CommitInfo commitInfo = userService.getCommitInfo(uid);

        model.addObject("projectList",projectList);
        model.addObject("users",user);
        model.addObject("all",commitInfo.getPass()+commitInfo.getNoPass());
        model.addObject("pass",commitInfo.getPass());
        model.addObject("readCount",commitInfo.getReadCount());

        model.setViewName("users/desc");
        return model;
    }

    /**
     * 投稿人所有文章
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(value = "author/list/{uid}")
    public ModelAndView authorList(ModelAndView model,Page page,@PathVariable("uid")Integer uid,HttpServletResponse response){
        Gson gson = new Gson();
        Optional<UserEntity> optionalUser = userRepository.findById(uid);
        if(!optionalUser.isPresent()){
            model.setViewName("error/404");
            response.setStatus(HttpStatus.SC_NOT_FOUND);
            return model;
        }
        UserEntity user = optionalUser.get();
        model = UserUtils.getMenuList(model,null);

        //获取首页分页信息
        TabelData<ProjectEntity> projectList =  projectService.getProjectByUserIdPage(page,user.getId());

        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));
        model.addObject("uid", uid);

        model.setViewName("users/list");

        return model;
    }

    /**
     * 本月排行榜前12人
     * @return
     */
    private List<AdminUserDto> getRankByMonth() {
        String beginDate = DateUtils.getMonthBegin() + " 00:00:00";
        String endDate = DateUtils.getMonthEnd() + " 23:59:59";

        //获取本月发布的项目
        List<ProjectEntity> projectList = projectRepository.findByWeek(beginDate, endDate);

        if(CollectionUtils.isEmpty(projectList)){
            return new ArrayList<>();
        }

        //记录各个用户ID发布的文章数量
        Map<Integer,Integer> countMap = new HashMap<>();
        for (ProjectEntity project : projectList) {
            Integer createId = project.getCreateId();
            Integer count = countMap.get(createId);
            if(count == null){
                count = 1;
            }else{
                count ++;
            }
            countMap.put(createId,count);
        }

        //排序
        Map<Integer, Integer> sortMap = CommonUtil.sortMapByValues(countMap);
        //只取前12个ID
        List<Integer> idList = new ArrayList<>(10);
        if(sortMap.size() > 10){
            int i = 1;
            for (Integer id : sortMap.keySet()) {
                if(i > 10){
                    break;
                }
                idList.add(id);
                i++;
            }
        }else{
            for (Integer id : sortMap.keySet()) {
                idList.add(id);
            }
        }

        //根据ID集合获取用户信息
        List<UserEntity> userList = userRepository.findByIdIn(idList);
        List<AdminUserDto> list = userList.stream().map(e -> userMapper.entityToDto(e)).collect(Collectors.toList());
        List<AdminUserDto> sortUserList = new ArrayList<>(list.size());
        for (Integer id : idList) {
            for (AdminUserDto user : list) {
                if(user.getId().intValue() == id.intValue()){
                    sortUserList.add(user);
                }
            }
        }
        return sortUserList;
    }


    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

    private Map<TypeDto, List<ProjectDto>> sortMapByKey(Map<TypeDto, List<ProjectDto>> map) {

        if (map == null || map.isEmpty()) {
            return null;
        }

        List<Map.Entry<TypeDto, List<ProjectDto>>> list = new ArrayList<Map.Entry<TypeDto, List<ProjectDto>>>(map.entrySet());

        Collections.sort(list,new Comparator<Map.Entry<TypeDto, List<ProjectDto>>>() {
            //升序排序
            public int compare(Map.Entry<TypeDto, List<ProjectDto>> o1,
                               Map.Entry<TypeDto, List<ProjectDto>> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }

        });

        LinkedHashMap<TypeDto, List<ProjectDto>> linkedHashMap = new LinkedHashMap<TypeDto, List<ProjectDto>>();

        // 将List中的数据存储到LinkedHashMap中
        for (Map.Entry<TypeDto, List<ProjectDto>> entry : list) {
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }

        return linkedHashMap;

    }

    /**
     * 搜索
     * @param key 文章标题
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(value = "search")
    public ModelAndView search(String key,ModelAndView model,Page page,HttpServletRequest request){

        Gson gson = new Gson();

        model = UserUtils.getMenuList(model,null);

        //获取首页分页信息
        TabelData<ProjectDto> projectList = new TabelData<>();
        if(!StrUtil.isBlank(key)){
            projectList =  projectService.getSerchPage(page,key);
            String ip = IPUtil.getIpAddr(request);
            String nowStr = DateUtil.format(new Date(), "yyyy-MM-dd");
            String begin = nowStr + " 00:00:00";
            String end = nowStr + " 23:59:59";
            List<SearchLogEntity> searchLogEntityList = searchLogRepository.findByIpAndWordAndCreateTimeAfterAndCreateTimeBefore(ip, key, DateUtil.parse(begin,"yyyy-MM-dd HH:mm:ss"), DateUtil.parse(end,"yyyy-MM-dd HH:mm:ss"));
            if(CollectionUtils.isEmpty(searchLogEntityList)){
                //如果今天搜素过该词就不保存
                if(!CommonUtil.isSpider(request)){
                    SearchLogEntity log = new SearchLogEntity();
                    log.setCreateTime(new Date());
                    log.setIp(ip);
                    log.setWord(key);
                    searchLogRepository.save(log);
                }
            }


        }

        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));
        model.addObject("key", key);

        model.setViewName("article/search");

        return model;
    }

    /**
     * 导航栏
     * @return
     */
    @GetMapping(value = "/menu")
    public String menu(){
        return "common/menu";
    }


    /**
     * 后台管理登录页面
     * @return
     */
    @GetMapping(value = "/admin")
    public String login(){
        return "admin/login";
    }


    /**
     * 获取验证码
     * @param request
     * @param response
     */
    @GetMapping("getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        }catch (Exception e){
            logger.error("获取验证码错误",e);
        }
    }

    /**
     * 获取验证码
     * @param request
     * @param response
     */
    @GetMapping("getEmailVerify")
    public void getEmailVerify(HttpServletRequest request, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getEmailRandcode(request, response);//输出验证码图片方法
        }catch (Exception e){
            logger.error("获取验证码错误",e);
        }
    }


    /**
     * 校验邮箱验证码是否正确
     * @return
     */
    @PostMapping(value = "emailCheckCode")
    @ResponseBody
    public R checkCode(HttpSession session, @RequestParam("code")String userCode){
        String code = session.getAttribute(RandomValidateCodeUtil.EMAILRANDOMCODEKEY).toString();

        if(code.equals(userCode)){
            //验证码正确
            return R.ok("验证码正确");
        }else{
            return R.error("验证码输入错误！");
        }

    }


    /**
     * 获取首页项目所需数据
     * @param page
     * @return
     */
    @RequestMapping(value = "getIndexData")
    @ResponseBody
    public TabelData<ProjectDto> getIndexData(Page page){
       return projectService.getIndexData(page);
    }


    /**
     * 获取网赚资讯所需数据
     * @param page
     * @return
     */
    @RequestMapping(value = "getNewsData")
    @ResponseBody
    public TabelData<ProjectDto> getNewsData(Page page,@RequestParam("typeId")Integer typeId){
        return projectService.getProjectByTypeIdPage(page,typeId,false);
    }

    /**
     * 获取普通项目（免费，投资）所需数据
     * @param page
     * @return
     */
    @RequestMapping(value = "getNormalProjectData")
    @ResponseBody
    public TabelData<ProjectDto> getNormalProjectData(Page page,@RequestParam("typeId")Integer typeId){
        return projectService.getProjectByTypeIdPage(page,typeId,false);
    }


    @RequestMapping(value = "goDownload")
    public String goDownLoad(){
        return  "download";
    }

    @RequestMapping(value="/download",method = RequestMethod.GET)
    public void download( HttpServletResponse response) throws Exception{
        //要上传的文件名字
        //通过文件的保存文件夹路径加上文件的名字来获得文件
//        apkName = new String(apkName.getBytes("UTF-8"), "iso-8859-1");
        //下载量+1
        sysDownService.addCount();

        String apkPath = OSSClientConstants.APK_PATH+apkName;
        InputStream is = ossServicec.getFileObj(OSSClientConstants.BUCKET_NAME,apkPath);
        //首先设置响应的内容格式是force-download，那么你一旦点击下载按钮就会自动下载文件了
        response.setContentType("application/force-download");
        //通过设置头信息给文件命名，也即是，在前端，文件流被接受完还原成原文件的时候会以你传递的文件名来命名
        response.addHeader("Content-Disposition","attachment; filename=" +new String(apkName.getBytes("UTF-8"), "iso-8859-1"));
        //进行读写操作
        byte[]buffer=new byte[1024];
        BufferedInputStream bis=null;
        try{
            bis = new BufferedInputStream(is);
            OutputStream os=response.getOutputStream();
            //从源文件中读
            int i=bis.read(buffer);
            while(i!=-1){
                //写到response的输出流中
                os.write(buffer,0,i);
                i=bis.read(buffer);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //善后工作，关闭各种流
            try {
                if(bis!=null){
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 跳转到标签
     * @return
     */
    @GetMapping(value = "tag")
    public ModelAndView tag(String key,HttpServletResponse response,HttpServletRequest request) throws Exception{
        request.setCharacterEncoding("UTF-8");
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com/tag/"+ URLEncoder.encode(key,"UTF-8"));
        return null;
    }

    /**
     * 跳转到标签
     * @return
     */
    @GetMapping(value = "tag/{key}")
    public ModelAndView tag2(ModelAndView model, @PathVariable("key")String key, Page page,HttpServletResponse response,HttpServletRequest request)throws Exception{

        Gson gson = new Gson();

        model = UserUtils.getMenuList(model,null);

        LabelEntity label = labelRepository.findByLabelName(key);
        if(label == null){
            model.setViewName("error/404");
            response.setStatus(HttpStatus.SC_NOT_FOUND);
            return model;
        }

        //相关标签的app
        List<AppLabelEntity> appLabelList = appLabelRepository.findByLabelId(label.getId());
        if(CollectionUtil.isNotEmpty(appLabelList)){
            List<Integer> appIdList = appLabelList.stream().map(e -> e.getAppId()).collect(Collectors.toList());
            List<AppEntity> appList = appRepository.findByIdInOrderByDownCountDesc(appIdList);
            List<AppDto> appDtoList = appList.stream().map(a -> {
                AppDto appDto = appMapper.entityToDto(a);
                if(!StringUtils.isEmpty(appDto.getCover())){
                    appDto.setCover(ossService.getImgUrl(appDto.getCover()));
                }
                return appDto;
            }).collect(Collectors.toList());
            model.addObject("appList",appDtoList);
        }

        //设置相似标签
        List<LabelEntity> labelList = labelRepository.findByLabelNameLike(key);
        model.addObject("likeKeyList",labelList);

        //获取最近更新
        List<ProjectDto> newProjectList = projectService.getNewProjectList(10);
        model.addObject("newProjectList", newProjectList);

        //获取标签页项目信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByKeyIdPage(page,String.valueOf(label.getId()));

        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(projectList.getData())){
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(),"yyyy-MM-dd'T'HH:mm:ss"));
        }

        boolean mobile = BrowserUtils.isMobile(request.getHeader("user-agent"));
        model.addObject("mobile", mobile);

        model.addObject("key",key);

        model.setViewName("article/tag");
        return model;
    }


    /**
     * 网站地图
     * @return
     */
    @RequestMapping(value = "sitemap.xml",produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public byte[] sitemap(){

        byte[] result;
        try {
            File file = new File(siteMapPath,siteMapName);
            InputStream in = new FileInputStream(file);

            result = IOUtils.toByteArray(in);
        }catch (Exception e){
            logger.info(e.getMessage());
            return null;
        }

        return result;
    }

    /**
     * 跳转到变现反馈列表页面
     * @return
     */
    @GetMapping(value = "getWithDrawList")
    public ModelAndView yangmao(ModelAndView model,Integer page,Integer limit,Integer projectId){
        model = UserUtils.getMenuList(model,null);
        Page pageObj = new Page();
        if(page != null){
            pageObj.setPage(page);
        }
        if(limit != null){
            pageObj.setLimit(limit);
        }

        Gson gson = new Gson();

        //获取首页分页信息
        TabelData<ProjectEntity> projectList =  projectService.getWithDrawListPage(pageObj,projectId);

        model.addObject("projectList", projectList.getData());
        pageObj.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(pageObj));

        model.setViewName("article/withdrawlist");
        return model;
    }


    /**
     * 跳转用户注册页面
     * @return
     */
    @GetMapping(value = "/admin/registerView")
    public ModelAndView userIndex(ModelAndView modelAndView){
        modelAndView.setViewName("admin/register");
        return modelAndView;
    }


    /**
     * 跳转到薅羊毛首页
     * @return
     */
    @GetMapping(value = "yangmao")
    public ModelAndView yangmao(ModelAndView model,Integer page,Integer limit,HttpServletRequest request,@RequestParam(required = false)Integer labelId){
        Gson gson = new Gson();
        Page page1 = new Page();
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 30;
        }
        page1.setPage(page);
        page1.setLimit(limit);

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,null);

        //2.获取项目排行按月榜单
        List<ProjectDto> rankProjectList = projectService.getRankProjectListByMonth(typeId);

        //获取首页分页信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByTypeIdAndLabelIdPage(page1,typeId,false, labelId);
        if(CollectionUtil.isNotEmpty(projectList.getData())){
            projectList.getData().stream().forEach(project ->{
                boolean showFlag = CommonUtil.in24Hour(new Date(),project.getCreateTime());
                project.setIsToday(showFlag == true ? "1":"0");
                if(project.getCreateTime() != null){
                    project.setShowCreateTime(TimeAgoUtils.format(CommonUtil.getDateByFormat(project.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));
                }
            });
        }

        List<TopProjectDto> topArticles = projectRepository.findCommendByTypeId(typeId);
        if(CollectionUtil.isNotEmpty(topArticles)){
            topArticles.stream().forEach(project ->{
                boolean showFlag = CommonUtil.in24Hour(new Date(),project.getCreateTime());
                project.setIsToday(showFlag == true ? "1":"0");
                if(project.getCreateTime() != null){
                    project.setShowCreateTime(TimeAgoUtils.format(CommonUtil.getDateByFormat(project.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));
                }
            });
        }

        List<LabelEntity> topLabelEntitys = labelRepository.findByType_IdAndIsTop(typeId, true);
        List<LabelDto> topLables = topLabelEntitys.stream().map(e -> labelMapper.entityToDto(e)).collect(Collectors.toList());

        //获取今日免费赚
        BigDecimal profitToday = projectService.getProfitToday();
        model.addObject("profitToday", profitToday);

        model.addObject("rankProjectList",rankProjectList);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("projectList", projectList.getData());
        page1.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page1));
        model.addObject("topArticles", topArticles);
        model.addObject("topLables", topLables);

        if(!CollectionUtils.isEmpty(projectList.getData())) {
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        }

        model.setViewName("article/yangmao/index");
        return model;
    }

    /**
     * 跳转到爆款好物首页
     * @return
     */
    @GetMapping(value = "shop")
    public ModelAndView shop(ModelAndView model,Page page,HttpServletRequest request){
        Gson gson = new Gson();

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,typeId);

        //2.获取项目排行榜单

        List<ProjectDto> rankProjectList = projectService.getRankProjectListByMonth(typeId);

        //获取首页分页信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByTypeIdPage(page,typeId,true);

        model.addObject("rankProjectList",rankProjectList);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(!CollectionUtils.isEmpty(projectList.getData())) {
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        }

        model.setViewName("article/shop/index");
        return model;
    }


    /**
     * 跳转到长期赚钱首页
     * @return
     */
    @GetMapping(value = "longtime")
    public ModelAndView longtime(ModelAndView model,Page page,HttpServletRequest request){
        Gson gson = new Gson();

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,typeId);

        //2.获取项目排行榜单

        List<ProjectDto> rankProjectList = projectService.getRankProjectListByMonth(typeId);

        //获取首页分页信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByTypeIdPage(page,typeId,false);
        List<TopProjectDto> topArticles = projectRepository.findCommendByTypeId(typeId);
        if(CollectionUtil.isNotEmpty(topArticles)){
            topArticles.stream().forEach(project ->{
                boolean showFlag = CommonUtil.in24Hour(new Date(),project.getCreateTime());
                project.setIsToday(showFlag == true ? "1":"0");
                if(project.getCreateTime() != null){
                    project.setShowCreateTime(TimeAgoUtils.format(CommonUtil.getDateByFormat(project.getCreateTime(),"yyyy-MM-dd HH:mm:ss")));
                }
            });
        }
        model.addObject("topArticles", topArticles);

        model.addObject("rankProjectList",rankProjectList);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(!CollectionUtils.isEmpty(projectList.getData())) {
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        }

        model.setViewName("article/longtime/index");
        return model;
    }


    /**
     * 跳转到数藏首页
     * @return
     */
    @GetMapping(value = "nft")
    public ModelAndView nft(ModelAndView model,Page page,HttpServletRequest request){
        Gson gson = new Gson();

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,typeId);

        //2.获取项目排行榜单

        List<ProjectDto> rankProjectList = projectService.getRankProjectListByMonth(typeId);

        //获取首页分页信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByTypeIdPage(page,typeId,true);

        model.addObject("rankProjectList",rankProjectList);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(!CollectionUtils.isEmpty(projectList.getData())) {
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        }

        model.setViewName("article/nft/index");
        return model;
    }



    /**
     * 跳转到网赚闲谈首页
     * @return
     */
    @GetMapping(value = "news")
    public ModelAndView news(ModelAndView model,Page page,HttpServletRequest request){
        Gson gson = new Gson();

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,typeId);

        //2.获取项目排行榜单
        List<ProjectDto> rankProjectList = projectService.getRankProjectListByMonth(typeId);

        //获取首页分页信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByTypeIdPage(page,typeId,false);

        model.addObject("rankProjectList",rankProjectList);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(!CollectionUtils.isEmpty(projectList.getData())) {
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        }
        model.setViewName("article/news/index");
        return model;
    }

    /**
     * 跳转到区块链首页
     * @return
     */
    @GetMapping(value = "blockChain")
    public ModelAndView blockChain(ModelAndView model,HttpServletRequest request,Page page){
        Gson gson = new Gson();

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,typeId);

        //2.获取项目排行榜单
        List<ProjectDto> rankProjectList = projectService.getRankProjectListByMonth(typeId);

        //获取首页分页信息
        TabelData<ProjectDto> projectList =  projectService.getProjectByTypeIdPage(page,typeId,false);
        //推荐app前10/最近更新app前10
        List<AppDto> topAppList = appService.findByTop(10,true);
        List<AppDto> newAppList = appService.findByCreateTime(10,true);
        model.addObject("topAppList", topAppList);
        model.addObject("newAppList", newAppList);
        boolean mobile = BrowserUtils.isMobile(request.getHeader("user-agent"));
        model.addObject("mobile", mobile);
        model.addObject("rankProjectList",rankProjectList);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("projectList", projectList.getData());
        page.setCount(projectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(!CollectionUtils.isEmpty(projectList.getData())){
            model.addObject("update", DateUtils.format(projectList.getData().get(0).getUpdateTime(),"yyyy-MM-dd'T'HH:mm:ss"));
        }

        model.setViewName("article/blockchain/index");
        return model;
    }


    /**
     * 跳转到区块链首页
     * @return
     */
    @GetMapping(value = "blockChain/app/{id}")
    public ModelAndView appDesc2(@PathVariable("id")Integer appId,HttpServletResponse response){
        response.setStatus(301);
        response.setHeader("Location", "https://www.daydayzhuan.com/app/"+appId);
        return null;
    }

    /**
     * 跳转到区块链首页
     * @return
     */
    @GetMapping(value = "app/{id}")
    public ModelAndView appDesc(ModelAndView model,@PathVariable("id")Integer appId,HttpServletResponse response,HttpServletRequest request){
        Optional<AppEntity> optionalAppEntity = appRepository.findById(appId);
        if(!optionalAppEntity.isPresent()){
            model.setViewName("error/404");
            response.setStatus(HttpStatus.SC_NOT_FOUND);
            return model;
        }
        AppEntity app = optionalAppEntity.get();
//        if(!CommonUtil.isSpider(request)){
//            app.setDownCount(app.getDownCount()+1);
//            appRepository.save(app);
//        }
        model = UserUtils.getMenuList(model,null);
        //获取关键字
        List<AppLabelEntity> appLabelList = appLabelRepository.findByAppId(appId);
        List<String> keywordList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(appLabelList)){
            List<Integer> labelIdList = appLabelList.stream().map(e -> e.getLabelId()).collect(Collectors.toList());
            List<LabelEntity> labelList = labelRepository.findByIdIn(labelIdList);
            keywordList = labelList.stream().map(l -> l.getLabelName()).collect(Collectors.toList());
        }
        if(!StringUtils.isEmpty(app.getCover())){
            app.setCover(ossService.getImgUrl(app.getCover()));
        }
        if(!StringUtils.isEmpty(app.getInviteImg())){
            app.setInviteImg(ossService.getImgUrl(app.getInviteImg()));
        }
        List<ProjectDto> projectList = projectService.findByAppId(appId);
        model.addObject("projectList",projectList);
        model.addObject("update",DateUtils.format(app.getUpdateTime(),"yyyy-MM-dd'T'HH:mm:ss"));
        model.addObject("app",app);
        model.addObject("createTime",DateUtils.format(app.getCreateTime(),"yyyy-MM-dd"));
        model.addObject("keywordList",keywordList);
        model.setViewName("article/blockchain/desc");
        return model;
    }

    /**
     * 跳转到长期赚钱首页
     * @return
     */
    @GetMapping(value = "subject")
    public ModelAndView subject(ModelAndView model,Page page,HttpServletRequest request){
        Gson gson = new Gson();

        String requestURI = CommonUtil.getUrl(request.getRequestURI());
        TypeDto type = typeService.findByUrl(requestURI);
        Integer typeId = type.getId();

        model = UserUtils.getMenuList(model,typeId);

        //app排行
        List<AppDto> appList = appService.findByTop(10,false);
        model.addObject("appList", appList);

        //获取首页分页信息
        TabelData<SubjectDto> subjectList =  subjectService.homePage(page);

        boolean mobile = BrowserUtils.isMobile(request.getHeader("user-agent"));
        model.addObject("mobile", mobile);
        model.addObject("rel_typeId",typeId);
        model.addObject("typeId",typeId);
        model.addObject("subjectList", subjectList.getData());
        page.setCount(subjectList.getCount());
        model.addObject("page", gson.toJson(page));

        if(!CollectionUtils.isEmpty(subjectList.getData())) {
            model.addObject("update", DateUtils.format(subjectList.getData().get(0).getUpdateTime(), "yyyy-MM-dd'T'HH:mm:ss"));
        }

        model.setViewName("article/subject/index");
        return model;
    }

    @PostMapping("app/updateCount")
    @ResponseBody
    public void updateCount(@RequestParam("appId") Integer appId){
        appService.updateCount(appId);
    }


    /**
     * 跳转到其它网站
     * @return
     */
    @GetMapping(value = "go")
    public ModelAndView go(ModelAndView model){
        model.setViewName("go");
        return model;
    }
}
